package org.longs.xls;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XlsRead {

    private final Sheet sheet;
    private List<String> title;

    public List<String> getTitle() {
        return title;
    }

    public XlsRead(String path) throws IOException {
        FileInputStream input = new FileInputStream(path); // 替换为实际的文件路径
        Workbook workbook = new HSSFWorkbook(input);
        sheet = workbook.getSheetAt(0);
        workbook.close();
        input.close();
    }


    public List<Map<String, String>> converter() throws IOException {
        boolean flag = true;
        List<Map<String, String>> mapList = new ArrayList<>();
        title = new ArrayList<>();
        // 遍历行
        for (Row row : sheet) {
            // 遍历单元格
            HashMap<String, String> map = new HashMap<>();
            if (flag) {
                for (Cell cell : row) {
                    title.add(cell.getStringCellValue());
                }
            } else {
                for (int i = 0; i < title.size(); i++) {
                    final Cell cell = row.getCell(i);
                    if (cell == null) {
                        continue;
                    }
                    CellType cellType = cell.getCellType();
                    if (cellType == CellType.NUMERIC) {
                        map.put(title.get(i), cell.getNumericCellValue() + "");
                    } else if (cellType == CellType.STRING) {
                        map.put(title.get(i), cell.getStringCellValue());
                    } else if (cellType == CellType.BOOLEAN) {
                        map.put(title.get(i), cell.getBooleanCellValue() + "");
                    }
                }
            }
            if (flag) {
                flag = false;
            } else {
                mapList.add(map);
            }
        }
        return mapList;
    }

}
